<template>
  <div class="myOrder">
    <Card _Title="我的订单" :_Size="16" :_Tabs="changeWay" @_Change="changeType" _More="全部订单" _Src="/user/home/orderCenter/myOrder"></Card>

    <!-- 搜索 筛选 -->
    <div class="search-box">
      <a-input-search :style="{width:'320px'}" placeholder="请输入订单号搜索" v-model="apiParams.keywords" search-button class="input-search" @search="getList">
        <template #button-icon>
          <svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 1024 1024"><path fill="currentColor" d="M1014.64 969.04L703.71 656.207c57.952-69.408 92.88-158.704 92.88-256.208c0-220.912-179.088-400-400-400s-400 179.088-400 400s179.088 400 400 400c100.368 0 192.048-37.056 262.288-98.144l310.496 312.448c12.496 12.497 32.769 12.497 45.265 0c12.48-12.496 12.48-32.752 0-45.263zM396.59 736.527c-185.856 0-336.528-150.672-336.528-336.528S210.734 63.471 396.59 63.471c185.856 0 336.528 150.672 336.528 336.528S582.446 736.527 396.59 736.527"/></svg>
        </template>
      </a-input-search>
    </div>
    <!--<a-spin :loading="loading" tip="加载中...">-->
    <div class="order-content">
      <div class="order-list" v-if="orderList && orderList.length" v-for="(order, onderIndex) in orderList" :key="onderIndex">
        <div class="order-header">
          <div>
            <div>
              <span class="order-status">{{ filterOrderStatus(order.orderStatus) }}</span>
              <a-tag type="border">{{filterOrderPromotion(order.orderPromotionType)}}</a-tag>
            </div>
            <div>订单号：{{ order.sn }} &nbsp; &nbsp; &nbsp;{{order.createTime}}</div>
          </div>
          <div>
              <span v-if="order.orderStatus === 'COMPLETED'">
                <svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24">
                  <path fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3 6h18m-2 0v14c0 1-1 2-2 2H7c-1 0-2-1-2-2V6m3 0V4c0-1 1-2 2-2h4c1 0 2 1 2 2v2m-6 5v6m4-6v6"/>
                </svg>
              </span>
            <span style="">{{ unitPrice(order.flowPrice, "￥") }}</span>
          </div>
        </div>
        <div class="order-body">
          <div class="goods-list">
            <div v-for="(goods, goodsIndex) in order.orderItems" :key="goodsIndex">
              <img @click="goodsDetail(goods.skuId, goods.goodsId)" class="hover-color" :src="goods.image" alt=""/>
              <div>
                <div class="hover-color" @click="goodsDetail(goods.skuId, goods.goodsId)">{{ goods.name }}</div>
                <div><span class="global-color">{{ unitPrice(goods.goodsPrice, "￥") }} </span> x {{ goods.num }}</div>
                <a-button v-if="goods.commentStatus === 'UNFINISHED'" @click="comment(order.sn, goodsIndex)" size="mini" type="text" status="success" style="position:relative;top:-18px;left:100px;margin-right:10px">评价</a-button>
                <a-button v-if="goods.complainStatus === 'NO_APPLY'" @click="complain(order.sn, goodsIndex)" size="mini" type="text" status="warning" style="position:relative;top:-18px;left:100px;">投诉</a-button>
              </div>
            </div>
          </div>
          <div class="shop-list">
            <span @click="goShopPage(order.storeId)">{{ order.storeName }}</span>
          </div>
          <div class="order-options">
            <!-- 订单基础操作 -->
            <a-button @click="orderDetail(order.sn)" size="mini" status="warning" type="primary">订单详情</a-button>
            <a-button @click="handleCancelOrder(order.sn)"  size="mini" status="danger" type="primary" v-if="order.allowOperationVO.cancel">取消订单</a-button>
            <a-button @click="goPay(order.tradeSn)" size="mini" status="success" type="primary" v-if="order.allowOperationVO.pay">去支付</a-button>
            <a-button @click="received(order.sn)" size="mini" status="warning" type="outline" v-if="order.allowOperationVO.rog">确认收货</a-button>
            <!-- 售后 -->
            <a-button v-if="order.groupAfterSaleStatus && order.groupAfterSaleStatus.includes('NOT_APPLIED')" @click="applyAfterSale(order.orderItems)" size="mini">申请售后</a-button>
          </div>
        </div>
      </div>
      <Empty v-else />
    </div>
    <!--</a-spin>-->

    <!--取消订单modal-->
    <a-modal v-model:visible="cancelAvail" width="600px">
      <template #title>请选择取消订单原因</template>
      <div class="">
        <a-radio-group v-model="cancelParams.reason" type="button" class="mb_10">
          <a-radio :value="item.reason"  v-for="item in cancelReason" :key="item.id">{{ item.reason }}</a-radio>
        </a-radio-group>
      </div>
      <template #footer>
        <a-button @click="cancelAvail = false">取消</a-button>
        <a-button @click="sureCancel" status="danger" type="primary">确定</a-button>
      </template>
    </a-modal>
    <!--申请售后modal-->
    <a-modal v-model:visible="afterSaleModal" width="600px">
      <template #title>请选择申请售后的商品</template>
      <div class="">
        <a-table :columns="columns" :data="goodsData" :pagination="false">
          <template #options="{ record }">
            <a-button size="mini" status="warning" type="outline" @click="toAfterSaleDetail(record)">选择</a-button>
          </template>
        </a-table>
      </div>
      <template #footer>
        <a-button @click="afterSaleModal = false">取消</a-button>
        <!--<a-button @click="sureCancel" status="danger" type="primary">确定</a-button>-->
      </template>
    </a-modal>

  </div>
</template>

<script setup lang="ts">
  import { useRouter } from 'vue-router';
  import { ref, onMounted, watch } from 'vue';
  import { getOrderList, sureReceived, cancelOrder } from '@/api/order';
  import { orderStatusList, orderPromotionList } from '../../pages/user/home/enumeration.js';
  import { unitPrice } from '@/utils/filters';
  import { Message, Modal } from '@arco-design/web-vue';
  import { afterSaleReason } from "@/api/member";

  const router = useRouter();
  const changeWay = ref(['全部订单', '未付款', '待收货/使用', '已完成']); // 订单状态
  // 请求参数
  const apiParams = ref({
    pageNumber: 1,
    pageSize: 5,
    keywords: '',
    tag: 'ALL',
  });
  const orderList = ref<Array<any>>([]);
  const total = ref(0);
  const loading = ref(false);
  // 取消订单modal
  const cancelAvail = ref(false);
  // 取消订单原因
  const cancelReason = ref<Array<any>>([]);
  // 取消订单参数
  const cancelParams = ref({orderSn: "", reason: "",});
  // 申请售后弹窗
  const afterSaleModal = ref(false);
  const goodsData = ref<Array<any>>([]);  // 商品数据
  const columns = [
    {title: '商品名称', dataIndex: 'name'},
    {title: '价格', dataIndex: 'goodsPrice'},
    {title: '操作', slotName: 'options'},
  ];

  // 切换订单状态
  const changeType = (index: any) => {
    switch (index) {
      case 0:
        apiParams.value.tag = 'ALL';
        break;
      case 1:
        apiParams.value.tag = 'WAIT_PAY';
        break;
      case 2:
        apiParams.value.tag = 'WAIT_ROG';
        break;
      case 3:
        apiParams.value.tag = 'COMPLETE';
        break;
    }
    apiParams.value.pageNumber = 1;
  };
  // 获取订单列表
  const getList = () => {
    let params = JSON.parse(JSON.stringify(apiParams.value));
    loading.value = true;
    getOrderList(params).then(res => {
      loading.value = false;
      if (res.data.success) {
        orderList.value = res.data.result.records;
        total.value = res.data.result.total;
      }
    });
  };

  // 跳转商品详情
  const goodsDetail = (skuId: any, goodsId: any) => {
    let routeUrl = router.resolve({path: "/goodsDetail", query: { skuId, goodsId },});
    window.open(routeUrl.href, "_blank");
  };
  // 评价
  const comment = (sn: any, goodsIndex: any) => {
    router.push({path: '/user/home/memberCenter/addComment', query: { sn, index: goodsIndex }})
  };
  // 投诉
  const complain = (sn: any, goodsIndex: any) => {
    router.push({path: '/user/home/memberCenter/complain', query: { sn, index: goodsIndex }})
  };
  // 跳转店铺首页
  const goShopPage = (id: any) => {
    let routeUrl = router.resolve({path: "/merchant", query: { id },});
    window.open(routeUrl.href, "_blank");
  };
  // 订单详情
  const orderDetail = (sn: any) => {
    router.push({path: `/user/home/orderCenter/orderDetail`, query: { sn }});
  };
  // 取消订单
  const handleCancelOrder = (sn: any) => {
    cancelParams.value.orderSn = sn;
    afterSaleReason("CANCEL").then((res) => {
      if (res.data.success) {
        cancelReason.value = res.data.result;
        cancelAvail.value = true;
        cancelParams.value.reason = cancelReason.value[0].reason;
      }
    });
  };
  // 取消订单确认
  const sureCancel = () => {
    // 确定取消
    cancelOrder(cancelParams.value).then((res) => {
      if (res.data.success) {
        Message.success("取消订单成功");
        getList();
        cancelAvail.value = false;
      }
    });
  };
  // 去支付
  const goPay = (sn: any) => {
    router.push({path: "/payment/payment", query: {orderType: "TRADE", sn}})
  };
  // 确认收货
  const received = (sn: any) => {
    Modal.confirm({
      title: '确认收货',
      content: `当前订单是否确认收到货物？`,
      okButtonProps: {
        type: "primary",
        status: "danger"
      },
      onOk: () => {
        sureReceived(sn).then(res => {
          if (res.data.success) {
            Message.success('确认收货成功');
            getList();
          }
        })
      }
    })
  };
  // 申请售后
  const applyAfterSale = (goodsItem: any) => {
    let arr = [] as any;
    goodsItem.forEach((e: any) => {
      if (e.afterSaleStatus === 'NOT_APPLIED') {arr.push(e)}
    });
    if (arr.length === 1) {
      router.push({path: '/user/home/orderCenter/applyAfterSale', query: { sn: arr[0].sn }})
    } else {
      goodsData.value = arr;
      afterSaleModal.value = true;
    }
  };
  const toAfterSaleDetail = (item: any) => {
    router.push({path: '/user/home/orderCenter/applyAfterSale', query: { sn: item.sn }})
  };

  const filterOrderStatus = (status: any) => { // 获取订单状态中文
    const ob = orderStatusList.filter(e => { return e.status === status });
    return ob && ob[0] ? ob[0].name : status
  };
  const filterOrderPromotion = (status: any) => { // 获取订单活动状态中文
    const ob = orderPromotionList.filter(e => { return e.status === status });
    return ob && ob[0] ? ob[0].name : status
  };

  onMounted(() => {
    getList();
  });

  watch(() => [apiParams],
    (val: any) => {
      getList();
    }, { deep: true }
  );
</script>

<style scoped lang="less">
  .search-box {
    display: flex;
    flex-direction: row-reverse;
  }


  .order-content {
    width: 100%;
    margin: 20px 0;
    .order-list {
      border: 1px solid #ddd;
      border-radius: 3px;
      margin-bottom: 10px;
      .order-header {
        display: flex;
        align-items: center;
        padding: 10px;
        justify-content: space-between;
        border-bottom: 1px solid #ddd;
        > div:nth-child(1) > div:nth-child(1) > .order-status {
          display: inline-block;
          width: 70px;
        }
        > div:nth-child(1) > div:nth-child(2) {
          font-size: 12px;
          color: #999;
          margin-top: 6px;
        }
        > div:nth-child(2) {
          display: flex;
          align-items: flex-end;
        }
        > div:nth-child(2) > span:nth-child(2) {
          margin-bottom: 1px;
          display: inline-block;
          margin-left: 10px;
        }
      }
      .order-body {
        display: flex;
        justify-content: space-between;
        color: #999;
        padding: 10px;
        .goods-list {
          width: 580px;
        }
        .goods-list > div {
          width: 500px;
          display: flex;
          margin-bottom: 10px;
          img {
            width: 60px;
            height: 60px;
            margin-right: 10px;
          }
          > div {
            flex: 1;
            > div:nth-of-type(2) {
              margin-top: 10px;
            }
          }
        }
        .shop-list {
          span {
            color: @link_color;
            cursor: pointer;
            font-size: 12px;
          }
        }
        .order-options {
          display: flex;
          flex-direction: column;
          .arco-btn {
            margin-bottom: 6px;
          }
        }
      }
    }
  }
</style>
